<?php
declare (strict_types=1);

namespace app\serviceapp;


use app\model\CategoryColorParam;
use app\model\Goods;
use app\model\GoodsColorParam;
use app\model\GoodsLabel;
use app\model\GoodsMatchParam;
use app\model\GoodsSizeParam;
use app\model\GoodsSmallImages;
use app\model\TSkuParam;
use app\model\TSubCategory;
use app\model\UserDetails;
use app\model\UserFavorite;
use app\model\UserFenggeScore;
use app\service\TUserMatchParamService;
use app\util\CacheHelper;
use think\facade\Cache;
use think\facade\Db;

/**
 * 商品处理服务
 * Class GoodsService
 * @package app\serviceapp
 */
class GoodsService
{
    protected static $user = [];
    protected static $score = 6;

    /**
     * 获取收藏商品列表
     * @param  array $param
     * @return array
     */
    public static function GoodsCollectList($param)
    {
        $list = Db::table('t_user_favorite')
            ->alias('uf')
            ->join('t_goods g', 'uf.goods_id = g.id')
            ->order('uf.create_time', 'desc')
            ->where('uf.user_id=:user_id', ['user_id' => $param['userId']])
            ->field('g.id as goodsId,g.title as goodsTitle,g.price as goodsPrice,g.shop_type_name as shopTypeName,g.shop_name as shopName,g.pict_url as goodsImg')
            ->paginate(['page' => $param['page'], 'list_rows' => $param['pageSize']])
            ->toArray();


        if (!empty($list['data'])) {
            foreach ($list['data'] as $k => $v) {
                $ratio = Db::table(GoodsMatchParam::$_table)
                    ->where('goods_id=:goods_id', ['goods_id' => $v['goodsId']])
                    ->column('ratio');
                $ratioR = $ratio ? $ratio[0] : '0.00';
                $goodsMatch = static::getGoodsScoreByGoodsId($v['goodsId'], $param['userId'], $ratioR);
                $list['data'][$k]['goodsMatch'] = $goodsMatch;

                $userCollect = Db::table(UserFavorite::$_table)->where(['user_id' => $param['userId'], 'goods_id' => $v['goodsId']])->find();
                if (!empty($userCollect)) {
                    $goodsCollect = 1;
                } else {
                    $goodsCollect = 0;
                }
                $goodsColorImg = GoodsColorParam::where(['goods_id' => $v['goodsId']])->column('pict_url');
                if (count($goodsColorImg) == 1) {
                    $list['data'][$k]['goodsImg'] = $goodsColorImg[0];
                } else {
                    $goodsImg = static::getGoodsFuseImgByGoodsId($v['goodsId'], $param['userId']);
                    if (!empty($goodsImg)) {
                        $list['data'][$k]['goodsImg'] = $goodsImg;
                    } else {
                        $goods['goodsImg'] = $goodsColorImg[0];
                    }
                }
                $list['data'][$k]['goodsCollect'] = $goodsCollect;
                $list['data'][$k]['goodsStatus'] = $goodsMatch >= static::$score ? 1 : 0;

                $goodsLabel = Db::name(GoodsLabel::$_table)->where(['goods_id' => $v['goodsId']])->column('label_name');
                $list['data'][$k]['goodsLabel'] = $goodsLabel;
            }
        } else {
            return json_ok((object)array(), 0);
        }

        return json_ok($list, 0);
    }

    /**
     * 商品详情
     * @param  string $goodsId 商品ID
     * @param  int $userId 0 为游客 否则不是游客
     * @return array
     */
    public static function GoodsDetails($goodsId, $userId = 0)
    {
        $goodsCollect = 0;
        $goodsMatch = '?';
        $goodsReason = [];
        $goodsTable = Goods::$_table;
        $goodsSmallTable = GoodsSmallImages::$_table;
        $goodsLabelTable = GoodsLabel::$_table;
        $goodsMatchParamTable = GoodsMatchParam::$_table;
        $userCollectTable = UserFavorite::$_table;
        $list = Db::table($goodsTable)
            ->alias('g')
            ->where('g.id=:id', ['id' => $goodsId])
            ->field('g.id,g.shop_type_name shopTypeName,g.shop_name shopName,g.pict_url pictUrl,g.title,g.zk_final_price zkFinalPrice,g.price,g.tb_goods_id tbGoodsId,g.tbk_item_url tbkItemUrl, category_id')
            ->find();
        if (empty($list)) {
            return json_error(10001, '商品未找到');
        }
        /*商品轮播图*/
        $list['rotationPic'] = Db::table($goodsSmallTable)
            ->alias('gsi')
            ->where('gsi.goods_id=:goods_id', ['goods_id' => $goodsId])
            ->field('gsi.detail_img_url detailImgUrl')
            ->find();
        $goodsColorImg = GoodsColorParam::where(['goods_id' => $goodsId])->column('pict_url');
        $goodsColorImgs = '';
        if (!empty($goodsColorImg)) {
            $goodsColorImgs = implode(',', $goodsColorImg);
        }
        $list['rotationPic']['imgUrl'] = $goodsColorImgs;
        $goodsScores = [];

        /*商品推荐理由*/
        if ($userId) {
            $goodsReason = Db::table($goodsLabelTable)
                ->where('goods_id=:goods_id', ['goods_id' => $goodsId])
                ->column('reason');
            $ratio = Db::table($goodsMatchParamTable)
                ->where('goods_id=:goods_id', ['goods_id' => $goodsId])
                ->column('ratio');
            $ratioR = $ratio ? $ratio[0] : '0.00';
            $goodsMatch = static::getGoodsScoreByGoodsId($goodsId, $userId, $ratioR);
            // todo
            if ($goodsMatch < static::$score) {
                $goodsReason = [];
            }
            $userCollect = Db::table($userCollectTable)->where(['user_id' => $userId, 'goods_id' => $goodsId])->find();
            if (!empty($userCollect)) {
                $goodsCollect = 1;
            }
            $scores = config('goods.score');
            // 风格的分数
            $styleScoreLast = GoodsService::getGoodsStyleScoreByGoodsId($ratioR, $scores);
            // 年龄的分数
            $ageScoreLast = GoodsService::getGoodsAgeScoreByGoodsId($goodsId, $userId, $scores);
            // 尺码的分数
            $sizeScoreLast = GoodsService::getGoodsSizeScoreByGoodsId($goodsId, $userId, $scores);
            // 细节的分数
            $xijieScoreLast = GoodsService::getGoodsXijieScoreByGoodsId($ratioR, $scores);
            // 体型的分数
            $tixingScoreLast = GoodsService::getGoodsTixingScoreByGoodsId($ratioR, $scores);
            // 肤色的分数
            $fuseScoreLast = GoodsService::getGoodsFuseScoreByGoodsId($goodsId, $userId, $scores);
            $deno = '9.9'; // 分母
            $cate = $list['category_id'] ?? 0;
            // 如果是鞋子 11 是鞋子分类
            $fengge = [
                // 风格
                'score' => bcdiv(bcmul($styleScoreLast, $deno, 2), $scores['style'], 1),
                'name' => '风格'
            ];
            $age = [
                // 年龄
                'score' => bcdiv(bcmul($ageScoreLast, $deno, 2), $scores['age'], 1),
                'name' => '年龄'
            ];
            $xijie = [
                // 细节
                'score' => bcdiv(bcmul($xijieScoreLast, $deno, 2), $scores['xijie'], 1),
                'name' => '细节'
            ];
            $tixing = [
                // 体型
                'score' => bcdiv(bcmul($tixingScoreLast, $deno, 2), $scores['tixing'], 1),
                'name' => '体型'
            ];
            $fuse = [
                // 肤色
                'score' => bcdiv(bcmul($fuseScoreLast, $deno, 2), $scores['color'], 1),
                'name' => '肤色'
            ];
            $chima = [
                // 尺码
                'score' => bcdiv(bcmul($sizeScoreLast, $deno, 2), $scores['size'], 1),
                'name' => '尺码'
            ];
            $goodsScores[] = $fengge;
            $goodsScores[] = $age;
            $goodsScores[] = $xijie;
            $goodsScores[] = $tixing;
            $goodsScores[] = $fuse;
            if (11 != $cate) {
                $goodsScores[] = $chima;
            }
        }

        $list['goodsMatch'] = $goodsMatch;
        $list['goodsStatus'] = $goodsMatch >= static::$score ? 1 : 0;
        $list['goodsCollect'] = $goodsCollect;
        $list['goodsReason'] = $goodsReason;

        /*一起搭配*/
        //TODO 硬编码确定数据格式
        $list['collocationGoods'] = [
            ['goodsId' => 999,
                'pic' => 'https://img.alicdn.com/bao/uploaded/i1/3098173863/O1CN01K7e4WV1ePIa7Mv9z3_!!0-item_pic.jpg',
                'price' => 125.0
            ],
            ['goodsId' => 999,
                'pic' => 'https://img.alicdn.com/bao/uploaded/i1/3098173863/O1CN01K7e4WV1ePIa7Mv9z3_!!0-item_pic.jpg',
                'price' => 125.0
            ],
        ];
        $list['scores'] = $goodsScores;
        return json_ok($list, 0);
    }

    /**
     * 获取搜索商品
     * @param  array $param
     * @return array
     */
    public static function getGoodsListBySearch($param)
    {
        $tableGoods = Goods::$_table;
        $lastGoodsList = Db::name($tableGoods)
            ->where([['title', 'like', '%' . $param['title'] . '%']])
            ->field(['id goodsId', 'title goodsTitle', 'price goodsPrice', 'pict_url goodsImg', 'season', 'shop_type_name shopTypeName', 'shop_name shopName'])
            ->select()
            ->toArray();
        if (empty($lastGoodsList)) {
            return [];
        }
        $userId = $param['userId'];
        // 查询符合风格的商品
        $goodsListByStyle = static::getGoodsByStyle($userId);
        // 风格都没有，则表示该用户还没有完成资料填写
        if (empty($goodsListByStyle)) {
            return [];
        }

        // 查询符合体型的商品
        $goodsListByTixing = static::getGoodsByTixing($userId);

        // 查询符合细节的商品
        $goodsListByXijie = static::getGoodsByXijie($userId);

        // 查询符合肤色的商品
        $goodsListByFuse = static::getGoodsByFuse($userId);

        $goodsListTotal = array_merge($goodsListByStyle, $goodsListByTixing, $goodsListByXijie, $goodsListByFuse);
        if (empty($goodsListTotal)) return [];

        $intersectData = array_intersect(array_column($goodsListTotal, 'goods_id'), array_column($lastGoodsList, 'goodsId'));

        $lastGoodsListData = [];

        $scores = config('goods.score');

        $tableGoodsLabel = GoodsLabel::$_table;
        $tableGoodsMatchParam = GoodsMatchParam::$_table;
        foreach ($lastGoodsList as $goods) {
            if (!in_array($goods['goodsId'], $intersectData)) continue;
            $goodsRatio = Db::name($tableGoodsMatchParam)->where(['goods_id' => $goods['goodsId']])->column('ratio');
            $ratio = empty($goodsRatio) ? '0.00' : $goodsRatio[0];
            $goodsLabel = Db::name($tableGoodsLabel)->where(['goods_id' => $goods['goodsId']])->column('label_name');

            // 年龄的分数
            $ageScoreLast = GoodsService::getGoodsAgeScoreByGoodsId($goods['goodsId'], $userId, $scores);
            if ($ageScoreLast == 0) continue;
            // 尺码的分数
            $sizeScoreLast = GoodsService::getGoodsSizeScoreByGoodsId($goods['goodsId'], $userId, $scores);
            if ($sizeScoreLast == 0) continue;

            $goodsScore = static::getGoodsScoreByGoodsId($goods['goodsId'], $param['userId'], $ratio);

            $goodsColorImg = GoodsColorParam::where(['goods_id' => $goods['goodsId']])->column('pict_url');
            if (count($goodsColorImg) == 1) {
                $goods['goodsImg'] = $goodsColorImg[0];
            } else {
                $goodsImg = static::getGoodsFuseImgByGoodsId($goods['goodsId'], $userId);
                if (!empty($goodsImg)) {
                    $goods['goodsImg'] = $goodsImg;
                } else {
                    $goods['goodsImg'] = $goodsColorImg[0];
                }
            }

            $lastGoodsListData[] = [
                'goodsId' => $goods['goodsId'],
                'goodsTitle' => $goods['goodsTitle'],
                'goodsPrice' => $goods['goodsPrice'],
                'shopTypeName' => $goods['shopTypeName'],
                'shopName' => $goods['shopName'],
                'goodsImg' => $goods['goodsImg'],
                'goodsMatch' => $goodsScore ?? '0.00',
                'goodsStatus' => $goodsScore >= static::$score ? 1 : 0,
                'goodsCollect' => 0,
                'goodsLabel' => $goodsLabel,
            ];
        }
        if (empty($lastGoodsListData)) {
            return [];
        }
        $list = getPage($lastGoodsListData, $param['page'], $param['pageSize']);
        return $list;
    }

    /**
     * 根据用户查询所有符合条件的商品
     * 只查询风格大于15的
     * @param $userId
     * @param $page
     * @param $cid
     */
    public static function getGoodsListByUserid($param)
    {
        $userId = $param['userId'];
        $page = $param['page'];
        $cid = $param['cid'];
        $oid = $param['oid']; // 场合ID
        $paramVal = getMatchParamByOid($oid);
        $priceMin = $param['priceMin']; // 最低价
        $priceMax = $param['priceMax']; // 最高价
        // 查询符合风格的商品
        $goodsListByStyle = static::getGoodsByStyle($userId);
        // 风格都没有，则表示该用户还没有完成资料填写
        if (empty($goodsListByStyle)) {
            return [];
        }

        // 查询符合体型的商品
        $goodsListByTixing = static::getGoodsByTixing($userId);

        // 查询符合细节的商品
        $goodsListByXijie = static::getGoodsByXijie($userId);

        // 查询符合肤色的商品
        $goodsListByFuse = static::getGoodsByFuse($userId);

        $goodsListTotal = array_merge($goodsListByStyle, $goodsListByTixing, $goodsListByXijie, $goodsListByFuse);

        // 计算分数
        // 只显示当前季节的
        // 低于6分不显示
        $goodsListLastTotal = [];
        $goodsRedisAsynKey = config('cachekeys.user_goods_asyn');
        $seasonsCache = config('season');

        $redis = new CacheHelper();
        $tableGoods = Goods::$_table;

        $scores = config('goods.score');

        foreach ($goodsListTotal as $goods) {
            // 年龄的分数
            $ageScoreLast = GoodsService::getGoodsAgeScoreByGoodsId($goods['goods_id'], $userId, $scores);
            if ($ageScoreLast == 0) continue;
            // 尺码的分数
            $sizeScoreLast = GoodsService::getGoodsSizeScoreByGoodsId($goods['goods_id'], $userId, $scores);
            if ($sizeScoreLast == 0) continue;

            $score = static::getGoodsScoreByGoodsId($goods['goods_id'], $userId, $goods['ratio']);
            if ($score < static::$score) {
                // todo
//                continue;
            }
            $redisData = [
                'userId' => $userId,
                'goodsId' => $goods['goods_id'],
                'score' => $score,
            ];
            $redis->lpush($goodsRedisAsynKey, json_encode($redisData));
            $goodsListLastTotal[] = [
                'goods_id' => $goods['goods_id'],
                'score' => $score
            ];
        }

        $cacheTime = 60;
        $goodsRedisKey = config('cachekeys.user_goods_id');

        foreach ($goodsListLastTotal as $gs) {
            $redis->setnx($goodsRedisKey . $gs['goods_id'] . ':' . $userId, $gs['score'], $cacheTime);
        }

        if (empty($goodsListLastTotal)) {
            return [];
        }

        $goodsIdLast = [];
        foreach ($goodsListLastTotal as $g) {
            $goodsIdLast[] = $g['goods_id'];
        }
        $where[] = ['id', 'in', $goodsIdLast];
        if ($cid) {
            $where[] = ['category_id', '=', $cid];
        }
        if ($priceMin) {
            // 如果最低价有，最高价也有
            if ($priceMax) {
                $where[] = ['price', 'between', [$priceMin, $priceMax]];
            } else {
                // 最高价没有
                $where[] = ['price', '>=', $priceMin];
            }
        } else {
            // 没有最低价
            if ($priceMax) {
                // 有最高价
                $where[] = ['price', '<=', $priceMax];
            }
        }

        $lastGoodsList = Db::name($tableGoods)
            ->where($where)
            ->field(['id goodsId', 'title goodsTitle', 'price goodsPrice', 'pict_url goodsImg', 'season', 'shop_type_name shopTypeName', 'shop_name shopName', 'category_id categoryId'])
            ->select()
            ->toArray();

        if (empty($lastGoodsList)) {
            return [];
        }

        $goodsCollectRedisKey = config('cachekeys.user_goods_id') . "COLLECT:";
        $user_collect_table = UserFavorite::$_table;
        $userCollect = Db::name($user_collect_table)->where(['user_id' => $userId])->column('goods_id');
        if (!empty($userCollect)) {
            foreach ($userCollect as $collect) {
                $redis->setnx($goodsCollectRedisKey . $collect . ':' . $userId, 1, $cacheTime);
            }
        }

        // 去除掉不是当前季节的
        $month = (int)date('m');
        $lastGoodsListData = [];

        $tableGoodsLabel = GoodsLabel::$_table;
        foreach ($lastGoodsList as $goods) {
            $seasons = $goods['season'];
            $seasonsArr = explode(',', $seasons);
            if (empty($seasons)) {
                continue;
            }
            if (!empty($seasonsArr)) {
                $sr = '';
                foreach ($seasonsArr as $s) {
                    if (empty($s)) continue;
                    $sr .= $seasonsCache[$s] . ',';
                }
                $sr = rtrim($sr, ',');
                $r = explode(',', $sr);
                if (!in_array($month, $r)) {
                    continue;
                }
            }
            // 适合场合筛选
            $goodsParamVal = GoodsMatchParam::where(['goods_id' => $goods['goodsId'], 'match_group_id' => 22])->column('param_val');
            if (!empty($paramVal)) {
                if (empty($goodsParamVal)) {
                    continue;
                } else {
                    $goodsParamVal = explode(',', $goodsParamVal[0]);
                    $isContain = array_intersect($goodsParamVal, $paramVal);
                    if (empty($isContain)) {
                        continue;
                    }
                }
            }
            $goodsScore = $redis->get($goodsRedisKey . $goods['goodsId'] . ':' . $userId);
            $goodsCollect = (int)$redis->get($goodsCollectRedisKey . $goods['goodsId'] . ':' . $userId);

            $goodsLabel = Db::name($tableGoodsLabel)->where(['goods_id' => $goods['goodsId']])->column('label_name');
            $goodsColorImg = GoodsColorParam::where(['goods_id' => $goods['goodsId']])->column('pict_url');
            if (count($goodsColorImg) == 1) {
                $goods['goodsImg'] = $goodsColorImg[0];
            } else {
                $goodsImg = static::getGoodsFuseImgByGoodsId($goods['goodsId'], $userId);
                if (!empty($goodsImg)) {
                    $goods['goodsImg'] = $goodsImg;
                } else {
                    $goods['goodsImg'] = $goodsColorImg[0];
                }
            }

            $lastGoodsListData[] = [
                'goodsId' => $goods['goodsId'],
                'goodsTitle' => $goods['goodsTitle'],
                'goodsPrice' => $goods['goodsPrice'],
                'shopTypeName' => $goods['shopTypeName'],
                'shopName' => $goods['shopName'],
                'goodsImg' => $goods['goodsImg'],
                'goodsMatch' => $goodsScore ?? '0.00',
                'goodsStatus' => $goodsScore >= static::$score ? 1 : 0,
                'goodsCollect' => $goodsCollect,
                'goodsLabel' => $goodsLabel,
            ];
        }
        if (empty($lastGoodsListData)) {
            return [];
        }
        $list = getPage($lastGoodsListData, $param['page'], $param['pageSize']);
        return $list;
    }

    /**
     * 计算商品的分数
     * @param $goodsId
     * @param $userId
     * @param $ratio
     * @return array|string
     */
    public static function getGoodsScoreByGoodsId($goodsId, $userId, $ratio)
    {
        if (empty($goodsId) || empty($userId)) {
            return [];
        }
        $ratio = $ratio ?? '0.00';
        $scores = config('goods.score');
        // 风格的分数
        $styleScoreLast = static::getGoodsStyleScoreByGoodsId($ratio, $scores);
        // 年龄的分数
        $ageScoreLast = static::getGoodsAgeScoreByGoodsId($goodsId, $userId, $scores);
        // 尺码的分数
        $sizeScoreLast = static::getGoodsSizeScoreByGoodsId($goodsId, $userId, $scores);
        // 细节的分数
        $xijieScoreLast = static::getGoodsXijieScoreByGoodsId($ratio, $scores);
        // 体型的分数
        $tixingScoreLast = static::getGoodsTixingScoreByGoodsId($ratio, $scores);
        // 肤色的分数
        $fuseScoreLast = static::getGoodsFuseScoreByGoodsId($goodsId, $userId, $scores);
        // 总分为各种累加
        $goodsScore = bcadd($styleScoreLast, $ageScoreLast, 2);
        $goodsScore = bcadd($goodsScore, $sizeScoreLast, 2);
        $goodsScore = bcadd($goodsScore, $xijieScoreLast, 2);
        $goodsScore = bcadd($goodsScore, $tixingScoreLast, 2);
        $goodsScore = bcadd($goodsScore, $fuseScoreLast, 2);
        $totalScore = round($goodsScore, 1) . '';
        return bcdiv($totalScore, '1', 1);
    }

    /**
     * 计算商品年龄的分数
     * @param $goodsId
     * @param $userId
     * @param $scores
     * @return string
     */
    public static function getGoodsAgeScoreByGoodsId($goodsId, $userId, $scores)
    {
        // todo 用户属性redis存储
        $userDetailTable = UserDetails::$_table;
        $userDetail = Db::name($userDetailTable)->where(['user_id' => $userId])->column('nianling');
        $ageLast = '0.00';
        if (empty($userDetail)) {
            return $ageLast;
        }
        $userAge = $userDetail[0] ?? 0;
        $ages = config('goods.match_param.age');
        $ageGroupId = $ages['groupId'];
        $ageRange = $ages['range'];
        $ageKey = 0;
        foreach ($ageRange as $ageK => $ageV) {
            if ($userAge >= $ageV[0] && $userAge <= $ageV[1]) {
                $ageKey = $ageK;
                break;
            }
        }
        $table_goods_match_param = GoodsMatchParam::$_table;
        $fitAges = Db::name($table_goods_match_param)->where(['goods_id' => $goodsId, 'match_group_id' => $ageGroupId])->column('param_val');
        if (empty($fitAges)) {
            return $ageLast;
        }
        $fitAgesArr = explode(',', $fitAges[0]);
        if (in_array($ageKey, $fitAgesArr)) {
            $ageLast = $scores['age'];
        }
        return $ageLast;
    }

    /**
     * 计算商品肤色的分数
     * @param $goodsId
     * @param $userId
     * @param $scores
     * @return string
     */
    public static function getGoodsFuseScoreByGoodsId($goodsId, $userId, $scores)
    {
        // todo 用户属性redis存储
        $userDetailTable = UserDetails::$_table;
        $userDetail = Db::name($userDetailTable)->where(['user_id' => $userId])->column('fuse');
        $fuseLast = '0.00';
        if (empty($userDetail)) {
            return $fuseLast;
        }
        $userFuse = $userDetail[0] ?? ''; // labelId
        if (empty($userFuse)) {
            return $fuseLast;
        }

        $cate = Goods::where(['id' => $goodsId])->column('category_id');
        if (empty($cate)) {
            return $fuseLast;
        }
        $cateId = $cate[0];
        $goodsColorData = GoodsColorParam::where(['goods_id' => $goodsId])->column('color_id');
        $categoryColorData = CategoryColorParam::where(['label_id' => $userFuse, 'category_id' => $cateId])->column('param_val');
        $categoryColors = implode(',', $categoryColorData);
        $categoryColorData = explode(',', $categoryColors);
        // $categoryColorData 完全包含 $goodsColorData
        $categoryColorData = array_unique($categoryColorData);
        $arr_diff = array_intersect($categoryColorData, $goodsColorData);
        // 只要有交集 则匹配上

        if (empty($arr_diff)) {
            return $fuseLast;
        }
        $arr_v = array_values($arr_diff);
        if (empty($arr_v)) return $fuseLast;

        if ($arr_v) {
            $fuseLast = $scores['color'];
        }
        return $fuseLast;
    }

    /**
     * 计算商品尺码的分数
     * @param $goodsId
     * @param $userId
     * @param $scores
     * @return string
     */
    public static function getGoodsSizeScoreByGoodsId($goodsId, $userId, $scores)
    {
        $userDetailTable = UserDetails::$_table;
        $userDetail = Db::name($userDetailTable)->where(['user_id' => $userId])->column('chima');
        $sizeLast = '0.00';
        if (empty($userDetail)) {
            return $sizeLast;
        }
        $userSize = $userDetail[0] ?? '';
        if (empty($userSize)) {
            return $sizeLast;
        }

        $table_goods_size_param = GoodsSizeParam::$_table;
        $fitSizeIds = Db::name($table_goods_size_param)->where(['goods_id' => $goodsId])->column('size_id');
        if (empty($fitSizeIds)) {
            return $sizeLast;
        }
        $sizes = TSkuParam::where([['id', 'in', $fitSizeIds]])->column('name');
        if (in_array($userSize, $sizes)) {
            $sizeLast = $scores['size'];
        }
        return $sizeLast;
    }

    /**
     * 计算商品风格的分数
     * @param $ratio
     * @param $scores
     * @return string
     */
    public static function getGoodsStyleScoreByGoodsId($ratio, $scores)
    {
        $styleScore = $scores['style'];
        // 风格最终得分
        $styleScoreLast = bcmul($styleScore, $ratio, 2);
        return $styleScoreLast;
    }

    /**
     * 计算商品体型的分数
     * @param $ratio
     * @param $scores
     * @return string
     */
    public static function getGoodsTixingScoreByGoodsId($ratio, $scores)
    {
        $styleScore = $scores['tixing'];
        // 体型最终得分
        $styleScoreLast = bcmul($styleScore, $ratio, 2);
        return $styleScoreLast;
    }

    /**
     * 计算商品细节的分数
     * @param $ratio
     * @param $scores
     * @return string
     */
    public static function getGoodsXijieScoreByGoodsId($ratio, $scores)
    {
        $styleScore = $scores['xijie'];
        // 体型最终得分
        $styleScoreLast = bcmul($styleScore, $ratio, 2);
        return $styleScoreLast;
    }

    /**
     * 根据用户风格查询商品
     * 只查询风格大于15的
     * @param $userId
     * @return [{"goods_id":1,"ratio":"0.1"}]
     */
    public static function getGoodsByStyle($userId)
    {
        // 获取该用户符合的labelId
        $fields = ['shaonv', 'youya', 'langman', 'ziran', 'gudian', 'xiju', 'shaonian', 'romantic', 'ruizhi', 'yiyuziran', 'qianwei'];
        $table = UserFenggeScore::$_table;
        $userFenggeScore = UserFenggeScore::name($table)->where(['user_id' => $userId])->field($fields)->find();
        if (empty($userFenggeScore)) {
            return [];
        }
        $labels = config('goods.labels');
        $labelIds = [];
        foreach ($fields as $field) {
            if ($userFenggeScore->$field >= 15) {
                $labelIds[] = $labels[$field];
            }
        }
        $userMatchParams = UserMatchParamService::getSubCidAndGroupIdByLabelId($labelIds);
        return $userMatchParams;
    }

    /**
     * 根据用户体型查询商品
     * @param $userId
     */
    public static function getGoodsByTixing($userId)
    {
        // todo 用户属性redis存储
        $userDetailTable = UserDetails::$_table;
        $labelIds = Db::name($userDetailTable)->where(['user_id' => $userId])->column('tixing');
        // 获取该用户符合的labelId
        if (empty($labelIds)) {
            return [];
        }

        $userMatchParams = UserMatchParamService::getSubCidAndGroupIdByLabelId($labelIds);
        return $userMatchParams;
    }

    /**
     * 根据用户肤色查询商品
     * @param $userId
     */
    public static function getGoodsByFuse($userId)
    {
        // todo 用户属性redis存储
        $userDetailTable = UserDetails::$_table;
        $labelIds = Db::name($userDetailTable)->where(['user_id' => $userId])->column('fuse');
        if (empty($labelIds)) {
            return [];
        }
        $goodsList = CategoryColorParamService::getColorIdByLabelIds($labelIds);
        if (empty($goodsList)) {
            return [];
        }
        $userMatchParams = [];
        foreach ($goodsList as $goodsId) {
            $ratio = GoodsMatchParamService::getRatioByGoodsId($goodsId);
            $userMatchParams[] = [
                'goods_id' => $goodsId,
                'ratio' => $ratio
            ];
        }
        return $userMatchParams;
    }

    /**
     * 根据用户细节查询商品
     * @param $userId
     */
    public static function getGoodsByXijie($userId)
    {
        // todo 用户属性redis存储
        $userDetailTable = UserDetails::$_table;
        $labelIdArr = Db::name($userDetailTable)->where(['user_id' => $userId])->column('xijie');
        // 获取该用户符合的labelId
        if (empty($labelIdArr)) {
            return [];
        }
        $labelIds = explode(',', $labelIdArr[0]);
        $userMatchParams = UserMatchParamService::getSubCidAndGroupIdByLabelId($labelIds);
        return $userMatchParams;
    }

    /**
     * 根据用户肤色筛选不同的商品首页图
     * @param $goodsId
     * @param $userId
     * @return string
     */
    public static function getGoodsFuseImgByGoodsId($goodsId, $userId)
    {
        // todo 用户属性redis存储
        $userDetailTable = UserDetails::$_table;
        $userDetail = Db::name($userDetailTable)->where(['user_id' => $userId])->column('fuse');
        $img = '';
        if (empty($userDetail)) {
            return $img;
        }
        $userFuse = $userDetail[0] ?? ''; // labelId
        if (empty($userFuse)) {
            return $img;
        }

        $cate = Goods::where(['id' => $goodsId])->column('category_id');
        if (empty($cate)) {
            return $img;
        }
        $cateId = $cate[0];
        $categoryColorData = CategoryColorParam::where(['label_id' => $userFuse, 'category_id' => $cateId])->column('param_val');
        if (empty($categoryColorData)) return $img;
        $categoryColors = implode(',', $categoryColorData);
        $categoryColorData = explode(',', $categoryColors);
        if (empty($categoryColorData)) return $img;
        $colorImgs = GoodsColorParam::where(['goods_id' => $goodsId])->where([['color_id', 'in', $categoryColorData]])->column('pict_url');
        if (empty($colorImgs)) return $img;
        return $colorImgs[0] ?? $img;
    }

    /**
     * 根据商品ID获取详情
     * @param $goodsId
     * @return array|null|\think\Model
     */
    public static function getGoodsDetail($goodsId)
    {
        return Goods::where(['id' => $goodsId])->find();
    }
}
